package com.telnetnz.ticketdesk.action.user;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.telnetnz.ticketdesk.action.base.BasicSessionPageLogAction;
import com.telnetnz.ticketdesk.bean.ProjectToUser;
import com.telnetnz.ticketdesk.bean.Ticket;
import com.telnetnz.ticketdesk.bean.User;
import com.telnetnz.ticketdesk.service.ProjectToUserService;
import com.telnetnz.ticketdesk.service.TicketService;
import com.telnetnz.ticketdesk.service.UserService;

public class UserAction extends BasicSessionPageLogAction
{
	private static Logger logger = Logger.getLogger(UserAction.class);

	public String doLanding()
	{
		RequestBean bean = new DefaultRequestBean();
		return viewUser(bean, getSession().getSession_uuid());
	}

	public String doView()
	{
		RequestBean bean = new DefaultRequestBean();
		long userId = bean.getLong("id", 0L);
		return viewUser(bean, userId);
	}

	private String viewUser(RequestBean bean, long userId)
	{
		User user = UserService.getUser(userId);
		if (user == null)
			return this.message_box(
					langRes.get("global.operation-fail"),
					langRes.get("user.user-not-exist", new String[]{bean.getRedirect()}),
					bean.getRedirect(),
					2);

		List<ProjectToUser> projectToUsers = ProjectToUserService.getByUserId(userId);
		List<Integer> projectIds = new ArrayList<Integer>(); // The ids for building the drop down list
		for (ProjectToUser projectToUser : projectToUsers)
		{
			projectIds.add(projectToUser.getProjectId());
		}

		List<Long> ownerIds = new ArrayList<Long>();
		ownerIds.add(userId);

		List<Ticket> tickets = TicketService.getByPageAndCondition(
				0, 
				10, 
				TicketService.ORDERBY_PRIORITY, 
				0, 
				projectIds, 
				0L, 
				0L, 
				ownerIds, 
				0L, 
				0L, 
				null, 
				null, 
				-1, 
				-1, 
				null, 
				null, 
				0L, 
				null, 
				null, 
				null, 
				null, 
				null, 
				null);

		put_page_key("tickets", tickets);
		put_page_key("user", user);
		put_page_key("languages", getLanguages());
		return SUCCESS;
	}
}
